package com.mayblackcat.dy.controller;

import com.mayblackcat.dy.FrontEndData.AjaxResult;
import com.mayblackcat.dy.constant.Constants;
import com.mayblackcat.dy.entity.User;
import com.mayblackcat.dy.exception.NotFoundException;
import com.mayblackcat.dy.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
//需要在controller层中配置，解决跨域问题
@CrossOrigin
public class LoginController {

    @Autowired
    private LoginService loginService;

    //返回用户
    @GetMapping("/getFriends")
    public AjaxResult getFriend(){
       List<User> userList=loginService.findByAll();

       return  new AjaxResult(AjaxResult.Type.SUCCESS,"success",userList);
    }

    //登录
    @PostMapping(value = "/login")
    //前端请求传Json对象则后端使用@RequestParam；
    //前端请求传Json对象的字符串则后端使用@RequestBody。
    public AjaxResult login(@RequestBody User user, HttpSession session) {

        AjaxResult ajaxResult=null;
        //验证用户名和密码是否正确,防止空指针
        Optional<User> userOptional = Optional.ofNullable(loginService.findByUser(user.getUserName(), user.getPassword()));
        User loginUser=null;
        if(userOptional.isPresent()){
            loginUser=userOptional.get();
        }else {
           throw new NotFoundException("不存在该用户！");
        }

        if (loginUser != null||loginUser.getStatus()==0) {
            loginUser.setPassword(null);
            loginUser.setStatus(1);
            session.setAttribute("user",loginUser);
            //设置session失效时间
            session.setMaxInactiveInterval(86400);

            ajaxResult=new AjaxResult(AjaxResult.Type.SUCCESS,"success",loginUser);
            return ajaxResult;
        }else{
            ajaxResult=new AjaxResult(AjaxResult.Type.ERROR,"fail",null);
        }

        return ajaxResult;

    }

    //注册
    @PostMapping("/register")
    public AjaxResult register(@RequestBody User user){
        System.out.println(user);
        AjaxResult ajaxResult=loginService.registerUser(user.getUserName(), user.getPassword(),user.getEmail(),user.getSex());
        return ajaxResult;
    }

    //退出登录
    @GetMapping("/logout")
    public Map<String,String> logout(HttpSession session) {
        User logout = (User) session.getAttribute("user");
        boolean flag = loginService.updateStatus(logout);
        HashMap<String,String> map=new HashMap<>();
        if (flag){
            session.removeAttribute("user");
            map.put("code","success");
        }else {
            session.removeAttribute("user");
            map.put("code","fail");
        }

        return map;
    }
}
